package com.hngy.minio.config;

import com.hngy.minio.properties.MinioConfigurationProperties;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.MinioProperties;
import io.minio.errors.*;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @name: MinioConfiguration
 * @Author: 提莫大熊猫
 * @Date: 2023/8/21
 */
@Configuration
@ComponentScan("com.hngy.minio.service")
@EnableConfigurationProperties(MinioConfigurationProperties.class)
public class MinioConfiguration {
    @Bean
    public MinioClient minioClient(MinioConfigurationProperties minioProperties) throws ServerException, InsufficientDataException,
            ErrorResponseException, IOException, NoSuchAlgorithmException,
            InvalidKeyException, InvalidResponseException, XmlParserException,
            InternalException {

        MinioClient client = MinioClient.builder()
                .endpoint(minioProperties.getEndpoint())
                .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                .build();
        if (!client.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucket()).build())) {
            client.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucket()).build());
        }
        return client;
    }
}
